package com.ssm.user.excel;

import com.ssm.entity.PageResult;
import com.ssm.tool.excel.BaseEasyExcelExport;
import com.ssm.user.convert.UserConvert;
import com.ssm.user.entity.po.UserPo;
import com.ssm.user.entity.req.UserPageReq;
import com.ssm.user.service.UserService;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;

@Component
public class UserExcelExport extends BaseEasyExcelExport<UserPo> {

    @Resource
    private UserService userService;

    /**
     * 数据导出
     */
    public void exportWithBigData(String fileName, Map<String, Object> conditions) {
        this.exportExcel(fileName, conditions);
    }

    /**
     * 获取导出的表头
     */
    @Override
    protected List<List<String>> getExcelHead() {
        List<List<String>> head = new ArrayList<>();
        //Collections.singletonList创建包含单个元素的不可变列表(不可修改的，即不能添加、删除或修改其中的元素)
        head.add(Collections.singletonList("用户编号"));
        head.add(Collections.singletonList("用户姓名"));
        return head;
    }

    /**
     * 计算导出数据的总数
     */
    @Override
    protected Long dataTotalCount(Map<String, Object> conditions) {
        return userService.queryCount(conditions);
    }

    /**
     * 每一个sheet存放的数据总数
     */
    @Override
    protected Long eachSheetTotalCount() {
        return 5000L;
    }

    /**
     * 每次写入sheet的总数
     */
    @Override
    protected Long eachTimesWriteSheetTotalCount() {
        return 2000L;
    }

    /**
     * 构建每次写入的数据
     * resultList 空集合，存放数据(测试只存入id和name)
     * queryCondition 查询条件
     * pageNo 本次查询的页码
     * pageSize 本次查询页容量
     */
    @Override
    protected void buildDataList(List<List<String>> resultList, Map<String, Object> queryCondition,
                                 Long pageNo, Long pageSize) {
        UserPageReq userPageReq = new UserPageReq();
        //如果queryCondition不为空，则设置查询条件
        userPageReq.setPageIndex(Integer.parseInt(pageNo.toString()));
        userPageReq.setPageSize(Integer.parseInt(pageSize.toString()));
        //将req转为dto

        PageResult<UserPo> userPage = userService.getUserPage(UserConvert.INSTANCE.convertPageReqToPageDto(userPageReq));
        //获取userpo对象集合
        List<UserPo> records = userPage.getRecords();
        if(!CollectionUtils.isEmpty(records)) {
            records.forEach(user -> { //测试，只存入id，name
                resultList.add(Arrays.asList(user.getId().toString(), user.getName()));
            });
        }
    }
}
